<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends Admin_Controller {
		private $dbconn;

		public function __construct(){  
			parent::__construct();
			$this->dbconn = $this->load->database('default',true);
		}

		public function index(){
			$get		=	$this->input->get();
			$field		=	"uid";//默认排序
			$orderin	=	'desc';
			//指定排序
			if(isset($get['field'])){
				$field = $get['field'];
				if(isset($get['order']) && !empty($get['order'])){
					$orderin = $get['order'];
				}
			}
			$order	=	$field.' '.$orderin;
			$url_	=	"&field=".$field.'&order='.$orderin;
			$nowpage=	1;

			$platform	=	isset($get['platform'])?$get['platform']:"";
			$phone_num	=	isset($get['phone_num'])?$get['phone_num']:"";
			$uid		=	isset($get['uid'])?$get['uid']:"";
			$nickname	=	isset($get['nickname'])?$get['nickname']:"";
			$where		=	!empty($platform)?"platform ='$platform'":"1=1";
			$where		.=	!empty($phone_num)?" and phone like '$phone_num%'":"";
			$where		.=	!empty($uid)?" and uid ='$uid'":"";
			$where		.=	!empty($nickname)?" and nickname like '%$nickname%'":"";

			$this->load->library('pagination');//加载分页标签
			if(isset($get[$this->pagination->query_string_segment])){
				if(!empty($get[$this->pagination->query_string_segment])){
					$nowpage	=	$get[$this->pagination->query_string_segment];
				}
			}
			
			$this->load->model('Pagequery_model');//加载分页数据model
			$table		=	"cfd_user_info";
			//$this->Pagequery_model->debug=true;
			$user_data	=	$this->Pagequery_model->page_query($this->dbconn,$table,$order,$this->pagesize,$where,$nowpage);
			
			$config['base_url']	  =	$this->get_url(array($this->pagination->query_string_segment));
			$config['total_rows'] = !empty($user_data)?$user_data[0]['Total']:0;
			$config['per_page']   = $this->pagesize;
			$config['do_jump']    = true;
			$config['use_page_numbers']=true;
			$this->pagination->initialize($config); 
			$this->data['page_html']	=	$this->pagination->create_links();
			$this->data['page']			=	'user/index';
			$this->data['page_data']	=	$user_data;
			$this->data['url']			=	$this->get_url(array('order','field',$this->pagination->query_string_segment));
			$this->data['get']			=	$get;
			$this->data['order']		=	$orderin;
			$this->data['field']		=	$field;
			$this->load->view('layout',$this->data);
		}


		public function check(){
			$this->load->library('Report_Class');
			$this->load->library('TicketClass');
			$get	=	$this->input->get();
			$days	=	isset($get['days'])?$get['days']:"0";

			$user_list	=	array();
			if($days=="all"){
				$sql	=	"SELECT COUNT(1) as num FROM cfd_user_info where 1=1 ";
				$query	=	$this->dbconn->query($sql);
				$total	=	$query->row_array();
				if(!empty($total)){
					$pageNum	=	100000;
					$totalpage	=	bcdiv($total['num'],$pageNum);
					$totalpage	=	$totalpage == 0?1:$totalpage;
					for($page=1;$page<=$totalpage;$page++){
						$preNum		=	$pageNum*($page-1);
						$sql		=	"SELECT uid,cny,nickname FROM cfd_user_info order by uid asc limit $preNum,$pageNum ";

						$query		=	$this->dbconn->query($sql);
						$user_arr	=	$query->result_array();
						$user_list	=	$this->userAbnormal($user_list,$user_arr);
					}
				}

			}else{
				$sdate		=	date("Y-m-d",strtotime("-$days days"));
				$user_arr	=	$this->report_class->getUserTrade($sdate);
				$user_list	=	$this->userAbnormal($user_list,$user_arr);
			}

			$this->data['page']			=	'user/check';
			$this->data['page_data']	=	$user_list;
			$this->load->view('layout',$this->data);
		}

		private function userAbnormal($user_list,$user_arr){
			$this->load->model('user_model');
			if(!empty($user_arr)) foreach($user_arr as $user){

					$uid		=	$user['uid'];
					if(!isset($user['cny'])){
						$user		=	$this->user_model->getUserByUid($uid);
					}
					$withdraw	=	$this->report_class->getTotalWithdraw("uid='$uid'");
					$deposit	=	$this->report_class->getTotalDeposit("uid='$uid'");

					$history_yk	=	$this->report_class->getCfdHistoryYk($uid);
					$fee		=	$this->report_class->getCfdFee($uid);
					$invite		=	$this->report_class->getCfdInvite($uid);

					$ticketCny	=	$this->ticketclass->getBuyTicketCny($uid);

					$chi_data		=	$this->report_class->getCfdChiInfo($uid);
					$chi_cny		=	0;
					if(!empty($chi_data))foreach($chi_data as $name=>$items){
						$chi_cny	=	isset($items['dtype']['cny'])?bcadd($items['dtype']['cny'],$chi_cny,2):$chi_cny;
					}
					
					$deserved	=	bcsub(bcadd(bcsub(bcsub(bcadd(bcsub($deposit,$withdraw,2),$history_yk,2),$chi_cny,2),$fee,2),$invite,2),$ticketCny,2);
					$diff_cny	=	abs(bcsub($user['cny'],$deserved,2));
					if($diff_cny >=1){
						$user_list[$uid]	=	array(
							'uid'		=>	$uid,
							'cny'		=>	$user['cny'],
							'nickname'	=>	$user['nickname'],
							'withdraw'	=>	$withdraw,
							'deposit'	=>	$deposit,
							'history_yk'=>	$history_yk,
							'fee'		=>	$fee,
							'invite'	=>	$invite,
							'chi_cny'	=>	$chi_cny,
							'ticketCny'	=>	$ticketCny,
							'deserved'	=>	$deserved,
						);
					}
				}

				return $user_list;
		}


		/**
		* 用户详细信息
		*/
		public function detail(){
			$get		=	$this->input->get();
			$uid		=	isset($get['uid'])?$get['uid']:"";

			$this->load->model('user_model');
			$user_info	=	$this->user_model->getUserByUid($uid);			  
			if(empty($user_info)){
				$this->alertMsg("用户不存在");
			}

			$last_login	=	$this->user_model->getObjectLog("login",$uid,1);
			if(!empty($last_login)){
				//加载文字处理类
				$this->load->library('ipoperation');
				$this->ipoperation->getIPArea($last_login[0]['ip']);
				$user_info['last_city']	=	$this->ipoperation->city;
				$user_info['last_time']	=	$last_login[0]['create_time'];	
			}else{
				$user_info['last_city']	=	"--";
				$user_info['last_time']	=	"--";	
			}

			$lock_arr=array();
			if($user_info['block']==1){//当前用户是锁定的
				$this->load->library('Admin_Class');
				$admin_id	=	$this->admin_info['admin_id'];
				$where_data	=	array(
					'uid'		=>	$uid,
					'remark'	=>	'block',
					'admin_id'	=>	$admin_id,
				);
				$lock_arr	=	$this->admin_class->getOperationLog($where_data);
			}

			//获取产品列表
			$this->load->model('product_model');
			$productList = $this->product_model->getProduct(array('status'=>1,'platform'=>'IB'),'all','stype DESC');

			//在线用户
			$this->load->model('online_model');
			$where_data	=	array("uid"=>$uid);	
			$online		=	$this->online_model->getOnline($where_data);
			$user_info['is_online']	=	!empty($online)?true:false;
			
			//个人账目统计
			$this->load->library('Report_Class');
			$cny['withdraw']	=	$this->report_class->getTotalWithdraw("uid='$uid'");
			$cny['deposit']		=	$this->report_class->getTotalDeposit("uid='$uid'");

			$this->load->library('TicketClass');
			$cny['ticketCny']	=	$this->ticketclass->getBuyTicketCny($uid);

			
			//获取本周盈亏
			$week			=   date('w');
			$start_date		=   date('Y-m-d',strtotime( '+'. 1-$week .' days' ));
			$end_date		=   date('Y-m-d 23:59:59',strtotime($start_date)+6*24*3600);
			$week_history_yk=	$this->report_class->getCfdHistoryYk($uid,$start_date,$end_date);			
			$history_yk		=	$this->report_class->getCfdHistoryYk($uid);
			$cny['cfd_fee']	=	$this->report_class->getCfdFee($uid);
			$cny['cfd_invite']	=	$this->report_class->getCfdInvite($uid);
			
			$chi_data		=	$this->report_class->getCfdChiInfo($uid);
			$chi_yk			=	0;
			$chi_cny		=	0;
			if(!empty($chi_data))foreach($chi_data as $name=>$items){
				$chi_yk		=	bcadd($items['yk'],$chi_yk,2);
				$chi_cny	=	isset($items['dtype']['cny'])?bcadd($items['dtype']['cny'],$chi_cny,2):$chi_cny;
			}
			
			$cfd_yk_arr	=	array();
			if(!empty($productList)) foreach($productList as $items){
				$cfd_history_yk				=	$this->report_class->getCfdHistoryYk($uid,"","",$items['name']);
				$cfd_yk_arr[$items['name']]	=	isset($chi_data[$items['name']]['yk'])?bcadd($cfd_history_yk,$chi_data[$items['name']]['yk'],2):$cfd_history_yk;
			}
			
			$cny['week_yk']	=	bcadd($week_history_yk,$chi_yk,2);
			$cny['history_yk']=	bcadd($history_yk,0,2);
			$cny['chi_yk']		=	$chi_yk;
			$cny['cfd_chi_bzj']	=	$chi_cny;
			$cny['total_yk']	=	bcadd($history_yk,$chi_yk,2);
			$cny['deserved']	=	bcsub(bcadd(bcsub(bcsub(bcadd(bcsub($cny['deposit'],$cny['withdraw'],2),$history_yk,2),$cny['cfd_chi_bzj'],2),$cny['cfd_fee'],2),$cny['cfd_invite'],2),$cny['ticketCny'],2);
			$cny['diff_cny']	=	abs(bcsub($user_info['cny'],$cny['deserved'],2));

			$this->data['week_start_date']	=	$start_date;
			$this->data['week_end_date']	=	$end_date;

			$this->data['page']			=	'user/detail';
			$this->data['user_info']	=	$user_info;
			$this->data['lock_arr']		=	$lock_arr;
			$this->data['productList']	=	$productList;
			$this->data['page_data']	=	array();
			$this->data['cny']			=	$cny;
			$this->data['chi_data']		=	$chi_data;
			$this->data['cfd_yk_arr']	=	$cfd_yk_arr;
			$this->data['get']			=	$get;
			$this->load->view('layout',$this->data);
	}

	//交易记录
	public function tradeLog(){
		$get		=	$this->input->get();
		$uid		=	isset($get['uid'])?$get['uid']:"";
		$kp			=	isset($get['kp'])?$get['kp']:"close";
		$sdate		=	isset($get['sdate'])?$get['sdate']:"";
		$edate		=	isset($get['edate'])?$get['edate']:"";

		$where		=	"1=1";
		$where		.=	!empty($uid)?" and uid='$uid'":"";
		$where		.=	!empty($kp)?" and kp='$kp'":"";
		$where		.=	!empty($sdate)?" and date>='$sdate'":"";
		$where		.=	!empty($edate)?" and date<='$edate'":"";
		$nowpage	=	1;

		$this->load->library('pagination');//加载分页标签
		if(isset($get[$this->pagination->query_string_segment])){
			if(!empty($get[$this->pagination->query_string_segment])){
				$nowpage	=	$get[$this->pagination->query_string_segment];
			}
		}

		//加载CFD配置
		$this->load->config('cfd');
		$sourceList = $this->config->item('sources');

		//获取产品列表
		$this->load->model('product_model');
		$productList = $this->product_model->getProduct(array('status'=>1,'platform'=>'IB'),'all','stype DESC');
		$productDesc = array();
		if(!empty($productList)) foreach($productList as $items){
			$productDesc[$items['name']]	=	$items['desc'];
		}
		
		//加载分页数据model
		$this->load->model('Pagequery_model');
		$table		=	"cfd_cfd_trade_log";
		$order		=	"date DESC";
		$trade_log	=	$this->Pagequery_model->page_query($this->dbconn,$table,$order,$this->pagesize,$where,$nowpage);


		$config['base_url']	  =	$this->get_url(array($this->pagination->query_string_segment));
		$config['total_rows'] = !empty($trade_log)?$trade_log[0]['Total']:0;
		$config['per_page']   = $this->pagesize;
		$config['do_jump']    = true;
		$config['use_page_numbers']=true;
		$this->pagination->initialize($config); 
		$this->data['page_html']	=	$this->pagination->create_links();
		$this->data['page']			=	'user/trade_log';
		$this->data['page_data']	=	$trade_log;
		$this->data['sourceList']	=	$sourceList;
		$this->data['productDesc']	=	$productDesc;
		$this->data['url']			=	$this->get_url(array('order','field',$this->pagination->query_string_segment));
		$this->data['get']			=	$get;
		$this->load->view('layout',$this->data);
	}

	//登录记录
	public function loginLog(){
		$get		=	$this->input->get();
		$uid		=	isset($get['uid'])?$get['uid']:"";
		$where		=	"uid='$uid'";
		$nowpage	=	1;

		if(empty($uid)){
			$this->alertMsg("用户不存在");
		}

		$this->load->library('pagination');//加载分页标签
		if(isset($get[$this->pagination->query_string_segment])){
			if(!empty($get[$this->pagination->query_string_segment])){
				$nowpage	=	$get[$this->pagination->query_string_segment];
			}
		}
		
		//加载分页数据model
		$this->load->model('Pagequery_model');
		$table		=	"cfd_".splitTable('log_login', $uid);
		$order		=	"create_time DESC";
		$logdb		=	$this->load->database('log',true);
		$login_log	=	$this->Pagequery_model->page_query($logdb,$table,$order,$this->pagesize,$where,$nowpage);

		//加载文字处理类
		$this->load->library('ipoperation');
		if(!empty($login_log))foreach($login_log as &$items){
			$this->ipoperation->getIPArea($items['ip']);
			$country	=	$this->ipoperation->country;
			$province	=	$this->ipoperation->province;
			$city		=	$this->ipoperation->city;
			if(empty($country)&&empty($province)&&empty($city))$items['area']="-------";
			else $items['area']	=	$country." ".$province." ".$city;
		}

		$config['base_url']	  =	$this->get_url(array($this->pagination->query_string_segment));
		$config['total_rows'] = !empty($login_log)?$login_log[0]['Total']:0;
		$config['per_page']   = $this->pagesize;
		$config['do_jump']    = true;
		$config['use_page_numbers']=true;
		$this->pagination->initialize($config); 
		$this->data['page_html']	=	$this->pagination->create_links();
		$this->data['page']			=	'user/login_log';
		$this->data['page_data']	=	$login_log;
		$this->data['url']			=	$this->get_url(array('order','field',$this->pagination->query_string_segment));
		$this->data['get']			=	$get;
		$this->load->view('layout',$this->data);
	}

	//期货账户流水
	public function userLog(){
		$get		=	$this->input->get();
		$uid		=	isset($get['uid'])?$get['uid']:"";
		$table		=	isset($get['table'])?$get['table']:"log_cny";
		$where		=	"uid='$uid'";
		$nowpage	=	1;

		if(empty($uid)){
			$this->alertMsg("用户不存在");
		}

		$this->load->library('pagination');//加载分页标签
		if(isset($get[$this->pagination->query_string_segment])){
			if(!empty($get[$this->pagination->query_string_segment])){
				$nowpage	=	$get[$this->pagination->query_string_segment];
			}
		}
		
		//加载分页数据model
		$this->load->model('pagequery_model');
		$table		=	"cfd_".splitTable($table, $uid);
		$order		=	"create_time DESC";
		$logdb		=	$this->load->database('log',true);
		$cny_log	=	$this->pagequery_model->page_query($logdb,$table,$order,$this->pagesize,$where,$nowpage);

		//加载文字处理类
		$this->load->library('ipoperation');
		if(!empty($cny_log))foreach($cny_log as $key=>$items){
			$this->ipoperation->getIPArea($items['ip']);
			$country	=	$this->ipoperation->country;
			$province	=	$this->ipoperation->province;
			$city		=	$this->ipoperation->city;
			if(empty($country)&&empty($province)&&empty($city)){
				$cny_log[$key]['area']="-------";
			}else{
				$cny_log[$key]['area']=	$country." ".$province." ".$city;
			}
		}

		//加载CFD配置
		$this->load->config('cfd');
		$sourceList = $this->config->item('sources');

		//获取产品列表
		$this->load->model('product_model');
		$productList = $this->product_model->getProduct(array('status'=>1,'platform'=>'IB'),'all','stype DESC');
		$productDesc = array();
		if(!empty($productList)) foreach($productList as $items){
			$productDesc[$items['name']]	=	$items['desc'];
		}

		$config['base_url']	  =	$this->get_url(array($this->pagination->query_string_segment));
		$config['total_rows'] = !empty($cny_log)?$cny_log[0]['Total']:0;
		$config['per_page']   = $this->pagesize;
		$config['do_jump']    = true;
		$config['use_page_numbers']=true;
		$this->pagination->initialize($config); 
		$this->data['page_html']	=	$this->pagination->create_links();
		$this->data['page']			=	'user/cny_log';
		$this->data['page_data']	=	$cny_log;
		$this->data['url']			=	$this->get_url(array('order','field',$this->pagination->query_string_segment));
		$this->data['get']			=	$get;
		$this->data['sourceList']	=	$sourceList;
		$this->data['productDesc']	=	$productDesc;

		$this->load->view('layout',$this->data);
	}

	/**
	* 删除用户
	*/
	public function deluser(){
		$get		=	$this->input->get();
		$uid		=	isset($get['uid'])?$get['uid']:"";
		$this->load->model('user_model');
		$user_info	=	$this->user_model->getUserByUid($uid);
		if(empty($user_info)){
			$this->alertMsg("用户不存在");
		}else{
			$checkdel	=	strstr($user_info['phone'],'[delete]');
			if(empty($checkdel)){
				$phone		=	'[delete]'.$user_info['phone'];
				$nickname	=	'[delete]'.$user_info['nickname'];
				$email		=	'[delete]'.$user_info['email'];
				$account	=	substr($user_info['account'],0, -3);
				$update_arr=array(
						'phone'		=>	$phone,
						'nickname'	=>	$nickname,
						'email'		=>	$email,
						'account'	=>	$account,
				);
				$where	=	array("uid"=>$uid);
				$rs		=	$this->user_model->updateUser($update_arr,$where);
				if($rs){
					$this->alertMsg("用户：$uid 删除成功！",'/user/index?sid='.$this->input->get('sid'));
				}else{
					$this->alertMsg("删除失败，请重试再试!");
				}
			}else{
				$this->alertMsg("用户:$uid 已经删除,请勿重复操作!");
			}
		}
	}

	//修改密码
	public function setPwd(){
		$post		=	$this->input->post();
		$uid		=	$post['uid'];
		$new_passwd	=	$post['new_passwd'];
		$new_passwd2=	$post['new_passwd2'];
		if(empty($new_passwd) || empty($new_passwd2)){
			$this->alertMsg("密码不能为空！");
		}

		if($new_passwd!=$new_passwd2){
			$this->alertMsg("两次密码不一致");
		}else{
			$this->load->model('user_model');
			$user_info	=	$this->user_model->getUserByUid($uid);
			if(empty($user_info)){
				$this->alertMsg("用户不存在");
			}else{
				$newpwd	=	generatePassword($new_passwd,$user_info['create_ip'],strtotime($user_info['create_time']));
				$up_arr = array(
					'password' => $newpwd,
				);
				$rs	=	$this->user_model->updateUser($up_arr,array('uid'=>$uid));
				if($rs){
					$this->load->library('Admin_Class');
					$this->load->library('PassPort');
					$data_arr	=	array(
							'admin_name'	=>	$this->admin_info['admin_name'],
							'admin_id'		=>	$this->admin_info['admin_id'],
							'action_time'	=>	date('Y-m-d H:i:s'),
							'uid'			=>	$uid,
							'action_memo'	=>	'修改用户登录密码',
					);
					$this->admin_class->addOperationLog($data_arr);
					$this->passport->flushUserCache($uid);
					$this->alertMsg("修改成功！");
				}else{
					$this->alertMsg("修改失败！");
				}
			}
		}
	}

	//冻结解冻帐号
	public function block(){
		$post	=	$this->input->post();
		$get	=	$this->input->get();
		$sid	=	isset($get['sid'])?$get['sid']:0;
		$uid	=	isset($post['uid'])?$post['uid']:0;
		$block	=	isset($post['block'])?$post['block']:0;
		$self_unlock=isset($post['self_unlock'])?$post['self_unlock']:0;
		if(empty($uid)){
			$this->alertMsg("UID错误，请重新再试!","/user/detail?sid=".$sid."&uid=".$uid);
		}

		$this->load->model('user_model');
		$user_info	=	$this->user_model->getUserByUid($uid);
		if(empty($user_info)){
			$this->alertMsg("用户不存在","/user/detail?sid=".$sid."&uid=".$uid);
		}

		if($block==1 && $user_info['block']==1){
			$this->alertMsg("该用户已被冻结，请勿重复操作！","/user/detail?sid=".$sid."&uid=".$uid);
		}

		if($block==0 && $user_info['block']==0){
			$this->alertMsg("该用户已被解冻，请勿重复操作！","/user/detail?sid=".$sid."&uid=".$uid);
		}

		$blockmemo	=	$post['blockmemo'];
		$date_time	=	date('Y-m-d H:i:s');
		$block_name	=	$block==1?"冻结账户":"解冻账户";
		$unblock	=	$block==1?0:1;
		
		$this->load->library('Admin_Class');
		$this->load->library('PassPort');
		if($block==0){
			$where_data	=	array(
				'uid'		=>	$uid,
				'remark'	=>	'block',
			);
			$lock_arr	=	$this->admin_class->getOperationLog($where_data);
			if($lock_arr['status']==1 && $lock_arr['admin_name'] !=$this->admin_info['admin_name']){
				$this->alertMsg("该用户已被".$lock_arr['admin_name']."限制解冻，解冻失败!","/user/detail?sid=".$sid."&uid=".$uid);
			}
		}

		$up_arr	=	array('block'=>$block);
		$rs		=	$this->user_model->updateUser($up_arr,array('uid'=>$uid,'block'=>$unblock));
		if($rs){
			$data_arr	=	array(
				'admin_name'	=>	$this->admin_info['admin_name'],
				'admin_id'		=>	$this->admin_info['admin_id'],
				'action_time'	=>	date('Y-m-d H:i:s'),
				'action_memo'	=>	$blockmemo,
				'remark'		=>	'block',
				'uid'			=>	$uid,
				'last_time'		=>	date('Y-m-d H:i:s'),
				'status'		=>	$self_unlock==1?1:0,
			);
			$this->passport->flushUserCache($uid);
			$this->admin_class->addOperationLog($data_arr);
			$this->alertMsg($block_name."成功！","/user/detail?sid=".$sid."&uid=".$uid);
		}else{
			$this->alertMsg($block_name."失败！","/user/detail?sid=".$sid."&uid=".$uid);
		}
	}

	/**
	* 提出在线用户
	*/
	public function delOnline(){
		$post	=	$this->input->post();
		$get	=	$this->input->get();
		$sid	=	isset($get['sid'])?$get['sid']:0;
		$uid	=	isset($post['uid'])?$post['uid']:0;

		$this->load->model('user_model');
		$user_info	=	$this->user_model->getUserByUid($uid);
		if(empty($user_info)){
			$this->alertMsg("用户不存在","/user/detail?sid=".$sid."&uid=".$uid);
		}
		$cooper		=	$user_info['cooper'];
		$platform	=	$user_info['platform'];

		$this->load->model('online_model');
		$data_arr	=	$this->online_model->getOnline(array('uid'=>$uid));
		
		$this->load->library('PassPort');
		$this->passport->setCooper($cooper);
		$this->passport->setPlatform($platform);
		if(!empty($data_arr))foreach($data_arr as $items){
			$skey	=	$items['skey'];
			$this->passport->kickOffline($skey);
		}
		
		$this->alertMsg("操作成功！","/user/detail?sid=".$sid."&uid=".$uid);
	}
}